package com.sunday.pinxinghui.model.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.OrderAdapter;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.Order;
import com.sunday.pinxinghui.model.WebViewActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Author by Damon,  on 2017/11/23.
 *
 */

public class OrderRefundActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;


    private long memberId;
    private int pageNo = 1, lastVisibleItem;

    private List<Order> dataSet = new ArrayList<>();
    private OrderAdapter orderAdapter;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;
    private int status;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_refund);
        ButterKnife.bind(this);
        titleView.setText("退款售后");
        status=5;
        memberId= BaseApplication.getInstance().getMember().getId();
        initRefreshLayout();
        getOrderList();
    }

    private void initRefreshLayout() {
        orderAdapter = new OrderAdapter(mContext, dataSet);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(orderAdapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.horizontal_space_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getOrderList();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == orderAdapter.getItemCount() && isCanloadMore) {
                    getOrderList();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        orderAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int p = (int) v.getTag();
                Order item = dataSet.get(p);
                switch (v.getId()) {
                    case R.id.item_view:
                        //订单详情
                        intent = new Intent(mContext, OrderDetailActivity.class);
                        intent.putExtra("orderId", item.getOrderId());
                        startActivity(intent);
                        break;
                    case R.id.order_btn1:
                        switch (item.getStatus()) {
                            case 4:
                            case 6:
                                //删除订单
                                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                                builder.setTitle("温馨提示");
                                builder.setMessage("确认删除订单吗？");
                                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();


                                    }
                                });
                                builder.show();
                                break;
                            case 0:
                                intent = new Intent(mContext, OrderPayActivity.class);
                                intent.putExtra("orderId", item.getOrderId());
                                intent.putExtra("totalMoney", String.format("%s", item.getTotalFee().setScale(2, RoundingMode.HALF_UP)));
                                startActivity(intent);
                                break;
                            case 1:
                                //申请退款
                                intent = new Intent(mContext, ApplyRefundActivity.class);
                                intent.putExtra("order", item);
                                intent.putExtra("type", 1);//申请退款
                                startActivity(intent);
                                break;
                            case 2:
                            case 11:
                                //确认收货

                                break;
                            case 3:
                                //评价
                                intent = new Intent(mContext, MakeCommentActivity.class);
                                intent.putExtra("order", item);
                                startActivity(intent);
                                break;
                            case 5:
                                //查看退款详情
                                intent = new Intent(mContext, RefundDetailActivity.class);
                                intent.putExtra("order", item);
                                startActivity(intent);
                                break;
                            case 8:
                                //查看退货详情
                                intent = new Intent(mContext, RefundDetailActivity.class);
                                intent.putExtra("order", item);
                                startActivity(intent);
                                break;
                        }
                        break;
                    case R.id.order_btn2:
                        switch (item.getStatus()) {
                            case 0:
                                //取消订单
                                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                                builder.setTitle("温馨提示");
                                builder.setMessage("确认取消订单吗？");
                                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();


                                    }
                                });
                                builder.show();
                                break;
                            case 2:
                                //查看物流
                                if (item.getSendMethod() == 1) {
                                    //品行专送
                                    //申请退货
                                    intent = new Intent(mContext, ApplyRefundActivity.class);
                                    intent.putExtra("order", item);
                                    intent.putExtra("type", 2);//申请退货
                                    startActivity(intent);
                                } else {
                                    intent = new Intent(mContext, WebViewActivity.class);
                                    String url = String.format("https://m.kuaidi100.com/index_all.html?type=%1$s&postid=%2$s", item.getExpressCode(), item.getExpressNo());
                                    intent.putExtra("url", url);
                                    intent.putExtra("title", "物流查询");
                                    startActivity(intent);
                                }
                                break;
                            case 11:
                                //申请退货
                                intent = new Intent(mContext, ApplyRefundActivity.class);
                                intent.putExtra("order", item);
                                intent.putExtra("type", 2);//申请退货
                                startActivity(intent);
                                break;

                        }
                        break;
                    case R.id.order_btn3:
                        //申请退货
                        intent = new Intent(mContext, ApplyRefundActivity.class);
                        intent.putExtra("order", item);
                        intent.putExtra("type", 2);//申请退货
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    private void getOrderList() {
        Call<ResultDO<List<Order>>> call = ApiClient.getApiAdapter().getOrderList(memberId,
                status, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<Order>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Order>>> call, Response<ResultDO<List<Order>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                ptrFrame.refreshComplete();
                ResultDO<List<Order>> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (resultDO.getResult().size() == Constants.PAGE_SIZE) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    dataSet.addAll(resultDO.getResult());
                    if (dataSet.size() == 0) {
                        emptyLayout.setNoDataContent("暂无订单");
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    }
                    orderAdapter.notifyDataSetChanged();
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }

            }

            @Override
            public void onFailure(Call<ResultDO<List<Order>>> call, Throwable t) {
                ptrFrame.refreshComplete();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });
    }


}
